import express from 'express';
import { ClassGrade } from '../models/ClassGrade.js';
import { Grade } from '../models/Grade.js';
import { Student } from '../models/Student.js';
import { upload } from '../middleware/upload.js';
import xlsx from 'xlsx';
import fs from 'fs';

const router = express.Router();
const classGradeModel = new ClassGrade();
const gradeModel = new Grade();
const studentModel = new Student();

// 创建班级成绩
router.post('/', (req, res) => {
  try {
    console.log('创建班级成绩记录:', req.body);
    
    const classGradeData = {
      ...req.body,
      id: Date.now(),
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString()
    };
    
    const newClassGrade = classGradeModel.create(classGradeData);
    
    res.json({
      success: true,
      data: newClassGrade
    });
  } catch (error) {
    console.error('创建班级成绩失败:', error);
    res.status(500).json({ 
      success: false,
      error: '创建失败' 
    });
  }
});

// 获取班级成绩列表
router.get('/', (req, res) => {
  try {
    console.log('获取班级成绩列表');
    
    const classGrades = classGradeModel.findAll();
    
    // 关联学生数据计算统计信息
    const students = studentModel.findAll();
    const classGradesWithStats = classGrades.map(classGrade => {
      const classStudents = students.filter(student => 
        student.className === classGrade.className
      );
      
      return {
        ...classGrade,
        actualStudentCount: classStudents.length,
        enrollmentRate: classStudents.length > 0 ? 
          Math.round((classGrade.totalStudents / classStudents.length) * 100) : 0
      };
    });
    
    res.json({
      success: true,
      data: classGradesWithStats
    });
  } catch (error) {
    console.error('获取班级成绩列表失败:', error);
    res.status(500).json({ 
      success: false,
      error: '获取失败' 
    });
  }
});

// 创建班级成绩
router.post('/', (req, res) => {
  try {
    console.log('创建班级成绩记录:', req.body);
    
    // 直接使用BaseModel的create方法，它会自动处理id、createdAt和updatedAt
    const newClassGrade = classGradeModel.create(req.body);
    
    res.json({
      success: true,
      data: newClassGrade
    });
  } catch (error) {
    console.error('创建班级成绩失败:', error);
    res.status(500).json({ 
      success: false,
      error: '创建失败' 
    });
  }
});

// 生成班级成绩统计
router.post('/generate', (req, res) => {
  try {
    const { className, courseCode, semester } = req.body;
    console.log('生成班级成绩统计:', { className, courseCode, semester });
    
    const grades = gradeModel.findAll();
    const students = studentModel.findAll();
    
    const classGrades = grades.filter(grade => 
      grade.className === className && 
      grade.courseCode === courseCode && 
      grade.semester === semester
    );
    
    if (classGrades.length === 0) {
      return res.status(404).json({ 
        success: false,
        error: '未找到相关成绩数据' 
      });
    }
    
    const scores = classGrades.map(grade => grade.totalGrade);
    const averageScore = scores.reduce((a, b) => a + b) / scores.length;
    const maxScore = Math.max(...scores);
    const minScore = Math.min(...scores);
    
    // 计算成绩分布
    const gradeDistribution = {
      '90-100': 0,
      '80-89': 0,
      '70-79': 0,
      '60-69': 0,
      '0-59': 0
    };
    
    scores.forEach(score => {
      if (score >= 90) gradeDistribution['90-100']++;
      else if (score >= 80) gradeDistribution['80-89']++;
      else if (score >= 70) gradeDistribution['70-79']++;
      else if (score >= 60) gradeDistribution['60-69']++;
      else gradeDistribution['0-59']++;
    });
    
    const passCount = scores.filter(score => score >= 60).length;
    const excellentCount = scores.filter(score => score >= 90).length;
    const passRate = (passCount / scores.length * 100).toFixed(1);
    const excellentRate = (excellentCount / scores.length * 100).toFixed(1);
    
    const classGradeData = {
      className,
      courseName: classGrades[0].courseName,
      courseCode,
      teacher: classGrades[0].teacher,
      semester,
      academicYear: classGrades[0].academicYear,
      totalStudents: classGrades.length,
      averageScore: parseFloat(averageScore.toFixed(1)),
      maxScore,
      minScore,
      passRate: parseFloat(passRate),
      excellentRate: parseFloat(excellentRate),
      gradeDistribution,
      status: 'published'
    };
    
    const newClassGrade = classGradeModel.create(classGradeData);
    
    res.json({
      success: true,
      data: newClassGrade
    });
  } catch (error) {
    console.error('生成班级成绩统计失败:', error);
    res.status(500).json({ 
      success: false,
      error: '生成失败' 
    });
  }
});

// 创建班级成绩
router.post('/', (req, res) => {
  try {
    const classGradeData = req.body;
    console.log('创建班级成绩:', classGradeData);
    
    // 从请求中获取学生成绩数据
    const studentGrades = classGradeData.studentGrades || [];
    
    // 计算统计信息
    let notCounted = 0;
    let failCount = 0;
    let directPromotionCount = 0;
    let averageScore = 0;
    let promotionRate = 0;
    
    if (studentGrades.length > 0) {
      // 计算不计数人数
      notCounted = studentGrades.filter(g => g.status === 'notCounted').length;
      
      // 计算不及格人数（状态为fail，或综合成绩<60且状态不是notCounted）
      failCount = studentGrades.filter(g => 
        g.status === 'fail' || (g.comprehensiveScore < 60 && g.status !== 'notCounted')
      ).length;
      
      // 计算直升人数
      directPromotionCount = studentGrades.filter(g => g.status === 'directPromotion').length;
      
      // 计算平均分（技能和理论两科的平均）
      const validScores = studentGrades
        .filter(g => g.status !== 'notCounted' && (g.skills > 0 || g.theory > 0))
        .map(g => (g.skills + g.theory) / 2);
      averageScore = validScores.length > 0 
        ? validScores.reduce((a, b) => a + b, 0) / validScores.length 
        : 0;
      
      // 计算升班率（及格人数 / 总人数 * 100）
      const passCount = studentGrades.filter(g => 
        g.status === 'pass' || (g.comprehensiveScore >= 60 && g.status !== 'notCounted')
      ).length;
      const totalCount = studentGrades.filter(g => g.status !== 'notCounted').length;
      promotionRate = totalCount > 0 ? (passCount / totalCount * 100) : 0;
    }
    
    // 构建班级成绩数据
    const newClassGradeData = {
      ...classGradeData,
      notCounted: notCounted,
      failCount: failCount,
      directPromotionCount: directPromotionCount,
      averageScore: parseFloat(averageScore.toFixed(2)),
      promotionRate: parseFloat(promotionRate.toFixed(2)),
      totalStudents: studentGrades.length,
      studentGrades: studentGrades, // 保存学生成绩数据
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString()
    };
    
    const newClassGrade = classGradeModel.create(newClassGradeData);
    
    res.json({
      success: true,
      data: newClassGrade
    });
  } catch (error) {
    console.error('创建班级成绩失败:', error);
    res.status(500).json({ 
      success: false,
      error: '创建失败',
      details: error.message 
    });
  }
});

// 导入学生成绩
router.post('/import-student-grades', (req, res, next) => {
  upload.single('file')(req, res, (err) => {
    if (err) {
      console.error('文件上传错误:', err);
      return res.status(400).json({
        success: false,
        error: err.message || '文件上传失败'
      });
    }
    next();
  });
}, async (req, res) => {
  let tempFilePath = null;
  
  try {
    console.log('收到导入请求 - 路径:', req.path, '原始URL:', req.originalUrl);
    console.log('请求文件:', req.file ? req.file.originalname : '无文件');
    
    if (!req.file) {
      console.log('错误: 没有收到文件');
      return res.status(400).json({ 
        success: false,
        error: '请选择要上传的文件' 
      });
    }

    tempFilePath = req.file.path;
    console.log('开始处理上传文件:', req.file.originalname, '路径:', tempFilePath);

    if (!fs.existsSync(tempFilePath)) {
      return res.status(400).json({ 
        success: false,
        error: '文件不存在或无法访问' 
      });
    }

    // 读取Excel文件
    const workbook = xlsx.readFile(tempFilePath);
    const sheetName = workbook.SheetNames[0];
    const worksheet = workbook.Sheets[sheetName];
    
    if (!worksheet) {
      throw new Error('无法读取工作表数据');
    }

    // 转换为JSON数据
    const data = xlsx.utils.sheet_to_json(worksheet, {
      defval: '',
      raw: false,
      blankrows: false
    });

    console.log('解析到的数据行数:', data.length);

    if (data.length === 0) {
      throw new Error('文件中没有数据');
    }

    // 解析学生成绩数据
    // 期望的列名：学号、姓名、技能、理论、综合成绩、面试、扣分、状态、异常状态、备注
    const studentGrades = [];
    const errors = [];

    data.forEach((row, index) => {
      try {
        // 尝试多种可能的列名格式
        const studentId = row['学号'] || row['studentId'] || row['student_id'] || '';
        const studentName = row['姓名'] || row['name'] || row['studentName'] || '';
        const skills = parseFloat(row['技能'] || row['skills'] || row['skill'] || 0) || 0;
        const theory = parseFloat(row['理论'] || row['theory'] || 0) || 0;
        const interview = parseFloat(row['面试'] || row['interview'] || 0) || 0;
        const deduction = parseFloat(row['扣分'] || row['deduction'] || 0) || 0;
        const status = row['状态'] || row['status'] || 'pass';
        const abnormalStatus = row['异常状态'] || row['abnormalStatus'] || '';
        const remarks = row['备注'] || row['remarks'] || '';

        if (!studentId || !studentName) {
          errors.push(`第${index + 2}行: 学号或姓名为空`);
          return;
        }

        // 计算综合成绩（如果未提供）
        let comprehensiveScore = parseFloat(row['综合成绩'] || row['comprehensiveScore'] || 0) || 0;
        if (comprehensiveScore === 0 && (skills > 0 || theory > 0)) {
          // 简单计算：技能和理论的平均值
          comprehensiveScore = (skills + theory) / 2;
        }

        studentGrades.push({
          studentId: String(studentId),
          studentName: String(studentName),
          skills: skills,
          theory: theory,
          comprehensiveScore: comprehensiveScore,
          interview: interview,
          deduction: deduction,
          status: String(status) || 'pass',
          abnormalStatus: abnormalStatus || '',
          remarks: remarks || ''
        });
      } catch (rowError) {
        errors.push(`第${index + 2}行: ${rowError.message}`);
      }
    });

    // 清理临时文件
    if (tempFilePath && fs.existsSync(tempFilePath)) {
      fs.unlinkSync(tempFilePath);
      tempFilePath = null;
    }

    if (studentGrades.length === 0) {
      return res.status(400).json({
        success: false,
        error: '未能解析出任何有效的学生成绩数据',
        details: errors
      });
    }

    // 计算统计信息
    const notCounted = studentGrades.filter(g => g.status === 'notCounted').length;
    const failCount = studentGrades.filter(g => 
      g.status === 'fail' || (g.comprehensiveScore < 60 && g.status !== 'notCounted')
    ).length;
    const directPromotionCount = studentGrades.filter(g => g.status === 'directPromotion').length;
    
    const validScores = studentGrades
      .filter(g => g.status !== 'notCounted' && (g.skills > 0 || g.theory > 0))
      .map(g => (g.skills + g.theory) / 2);
    const averageScore = validScores.length > 0 
      ? validScores.reduce((a, b) => a + b, 0) / validScores.length 
      : 0;
    
    const passCount = studentGrades.filter(g => 
      g.status === 'pass' || (g.comprehensiveScore >= 60 && g.status !== 'notCounted')
    ).length;
    const totalCount = studentGrades.filter(g => g.status !== 'notCounted').length;
    const promotionRate = totalCount > 0 ? (passCount / totalCount * 100) : 0;

    res.json({
      success: true,
      data: {
        studentGrades: studentGrades,
        stats: {
          total: studentGrades.length,
          notCounted: notCounted,
          failCount: failCount,
          directPromotionCount: directPromotionCount,
          averageScore: parseFloat(averageScore.toFixed(2)),
          promotionRate: parseFloat(promotionRate.toFixed(2))
        }
      },
      errors: errors.length > 0 ? errors : undefined
    });

  } catch (error) {
    console.error('导入学生成绩失败:', error);
    
    // 清理临时文件
    if (tempFilePath && fs.existsSync(tempFilePath)) {
      try {
        fs.unlinkSync(tempFilePath);
      } catch (unlinkError) {
        console.error('删除临时文件失败:', unlinkError);
      }
    }
    
    res.status(500).json({ 
      success: false,
      error: '导入失败',
      details: error.message 
    });
  }
});

export default router;